package com.gzxw.mogublog.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzxw.mogublog.base.holder.RequestHolder;
import com.gzxw.mogublog.commons.entity.File;
import com.gzxw.mogublog.commons.entity.User;
import com.gzxw.mogublog.commons.feign.PictureFeignClient;
import com.gzxw.mogublog.utils.*;
import com.gzxw.mogublog.xo.service.SystemConfigService;
import com.gzxw.mogublog.xo.service.UserService;
import com.gzxw.mogublog.xo.service.WebConfigService;
import com.gzxw.mogublog.xo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Autowired
    private WebConfigService webConfigService;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemConfigService systemConfigService;

    @Value(value = "${BLOG.USER_TOKEN_SURVIVAL_TIME}")
    private Long userTokenSurvivalTime;


    @PostMapping("/login")
    public String login(@RequestBody UserVO userVO) {

//        webConfigService.
        // 获取用户名
        String userName = userVO.getUserName();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq("user_name", userName).or().eq("email", userName));
        queryWrapper.last("limit 1");
        User user = userService.getOne(queryWrapper);

        if (user == null || user.getStatus() == 0) {
            return ResultUtil.result("error", "用户不存在，请注册!");
        }

        if (user.getStatus() == 2) {
            return ResultUtil.result("error", "用户未激活");
        }

        // 如果能从数据库中查出来，说明该用户存在,然后判断密码是否正确
        if (StringUtils.isNotEmpty(user.getPassWord()) && user.getPassWord().equals(MD5Utils.string2MD5(userVO.getPassWord()))) {
            // 更新登录信息
            HttpServletRequest request = RequestHolder.getRequest();
            String ip = IpUtils.getIpAddr(request);
            Map<String, String> userMap = IpUtils.getOsAndBrowserInfo(request);
            user.setBrowser(userMap.get("BROWSER"));
            user.setOs(userMap.get("OS"));
            user.setLastLoginIp(ip);
            user.setLastLoginTime(new Date());
            // 登录成功后，次数+1
            Integer count = user.getLoginCount() + 1;
            user.setLoginCount(count);
            user.updateById();
            // 获取用户头像
            if (StringUtils.isNotEmpty(user.getAvatar())) {
                String message = pictureFeignClient.getPicture(user.getAvatar()).getMessage();
                File file = JSON.parseObject(message, File.class);
                if (file != null) {
                    user.setPhotoUrl(file.getPicUrl());
                }
            }
            // 生成token
            String token = StringUtils.getUUID();
            // 过滤密码
            user.setPassWord("");
            //将从数据库中查询到的数据缓存到redis中
            redisUtil.setEx("USER_TOKEN"+":"+token,JsonUtils.objectToJson(user),userTokenSurvivalTime, TimeUnit.HOURS);
            log.info("登录成功，返回token: "+token);
            return ResultUtil.result("success",token);
        } else {
            return ResultUtil.result("error", "账号或密码错误");
        }

    }
}
